﻿using System;
using System.IO;
using System.Configuration;

namespace Rison.DBHelper
{
    internal sealed class DbExecuteLog
    {
        private static DbExecuteLog _instance = null;

        private string logPath = string.Empty;

        private DbExecuteLog()
        {
            GetLogPath();
        }

        private void GetLogPath()
        {
            try
            {
                logPath = ConfigurationSettings.AppSettings["DatabaseLogPath"];
                if (string.IsNullOrEmpty(logPath))
                    logPath = "File\\Log\\DbLog\\";
                if (!logPath.EndsWith("\\"))
                    logPath += "\\";

                string appRootPath = System.Web.HttpContext.Current.Server.MapPath("~/");
                if (!appRootPath.EndsWith("\\") && !logPath.StartsWith("\\"))
                    appRootPath += "\\";

                logPath = appRootPath + logPath;

                DirectoryInfo info = new DirectoryInfo(logPath);
                if (!info.Exists)
                    info.Create();

                info = null;
            }
            catch { }
        }

        static DbExecuteLog()
        {
            _instance = new DbExecuteLog();
        }

        public static DbExecuteLog Instance
        {
            get { return _instance; }
        }

        public void CreateLog(string logContent)
        {
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(logPath + "log" + DateTime.Now.ToString("yyyy.MM.dd") + ".ini", true);
                sw.WriteLine("***********************************************************************");
                sw.WriteLine("log at : " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                sw.WriteLine(logContent);
                sw.WriteLine();
            }
            catch (Exception ex)
            {
                string m = ex.Message;
            }
            finally
            {
                try
                {
                    sw.Close();
                }
                catch { }
            }

        }       

    }
}
